//usage:
//生成key：bootnode -genkey bootnode.key
//启动bootnode: bootnode -nodekey=bootnode.key
//运行p2pdemo 1: p2pdemo --port 3401 --bootnode
//运行p2pdemo 2: p2pdemo --port 3402 --bootnode
package main
import (
	"fmt"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/p2p"
	"github.com/ethereum/go-ethereum/p2p/discover"
	"gopkg.in/urfave/cli.v1"
	"log"
	"math/rand"
	"os"
	"sync"
	"time"

)
var (
	port     int
	bootnode string
	name string
)
const (
	msgCodeRandNum = 0
	msgLength      = iota
)
func main() {
	app := cli.NewApp()
	app.Name = "p2pdemo"
	app.Usage = "p2p package demo"
	app.Action = startP2pNode
	app.Flags = []cli.Flag{
		cli.IntFlag{Name: "port", Value: 3401, Usage: "listen port", Destination: &port},
		cli.StringFlag{Name: "bootnode", Value: "", Usage: "boot node", Destination: &bootnode},
		cli.StringFlag{Name: "name", Value: "", Usage: "name", Destination: &name},
	}
	//if bootnode == ""{
	//	log.Fatal("bootnode should not empty")
	//}


	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}
func startP2pNode(c *cli.Context) error {
	fmt.Println(port)
	if bootnode == ""{
		log.Fatal("bootnode should not empty")
	}

	emitter := NewEmitter()
	nodeKey, _ := crypto.GenerateKey()
	node := p2p.Server{
		Config: p2p.Config{
			MaxPeers:   100,
			PrivateKey: nodeKey,
			Name:       name,
			ListenAddr: fmt.Sprintf(":%d", port),
			Protocols:  []p2p.Protocol{emitter.MyProtocol()},
		},
	}
	bootNode, err := discover.ParseNode(bootnode)
	if err != nil {
		return err
	}
	node.Config.BootstrapNodes = []*discover.Node{bootNode}
	if err := node.Start(); err != nil {
		return err
	}
	emitter.self = node.NodeInfo().ID[:8]
	go emitter.loopSendMsg()
	select {}
	return nil
}
func (e *Emitter) MyProtocol() p2p.Protocol {
	return p2p.Protocol{
		Name:    "rad",
		Version: 1,
		Length:  msgLength,
		Run:     e.msgHandler,
	}
}
type peer struct {
	peer *p2p.Peer
	ws   p2p.MsgReadWriter
	online bool
}
type Emitter struct {
	self  string
	peers map[string]*peer
	sync.Mutex
}
func NewEmitter() *Emitter {
	return &Emitter{peers: make(map[string]*peer)}
}
func (e *Emitter) addPeer(p *p2p.Peer, ws p2p.MsgReadWriter) {
	e.Lock()
	defer e.Unlock()
	id := fmt.Sprintf("%x", p.ID().String()[:8])
	//id := fmt.Sprintf("%x", name)
	e.peers[id] = &peer{ws: ws, peer: p, online:true}
}
func (e *Emitter) loopSendMsg() {
	for {
		func() {
			e.Lock()
			defer e.Unlock()
			msg := fmt.Sprintf("%s says: %s_%d", name,e.self, rand.Int())
			for _, p := range e.peers{
				if p.online{
					//fmt.Println(p.peer.Name())
					if err := p2p.SendItems(p.ws, msgCodeRandNum, msg); err != nil {
						log.Println("Emitter.loopSendMsg p2p.SendItems err", err, "peer id", p.peer.ID())
						p.online = false
						//continue
					}else{
						//log.Println("write msg to :",p.peer.RemoteAddr(),msg)
						p.online = true
					}

				}

			}
		}()
		time.Sleep(time.Second * 3)
	}
}
func (e *Emitter) msgHandler(peer *p2p.Peer, ws p2p.MsgReadWriter) error {
	e.addPeer(peer, ws)
	fmt.Println("addPeer",peer.RemoteAddr())
	for {

		msg, err := ws.ReadMsg()

		if err != nil {

			return err
		}
		switch msg.Code {
		case msgCodeRandNum:
			var myMessage []string
			if err := msg.Decode(&myMessage); err != nil {
				log.Println("decode msg err", err)
			} else {
				log.Println("read msg:", myMessage[0])
			}
		default:
			log.Println("unkown msg code")
		}
	}

	return nil
}